<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单流水号" prop="orderSn">
        <el-input
          v-model="queryParams.orderSn"
          placeholder="请输入订单流水号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>



      <el-form-item label="会员名" prop="userName">
        <el-select v-model="queryParams.userName" placeholder="请选择会员名" clearable>
          <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.userName"
              :value="user.userName"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="订单状态" prop="orderState">
        <el-select v-model="queryParams.orderState" placeholder="请选择订单状态" clearable>
          <el-option
            v-for="dict in dict.type.order_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['order:order:add']"
        >新增</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['order:order:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['order:order:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['order:order:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="id" />
      <el-table-column label="订单流水号" align="center" prop="orderSn" />
      <el-table-column label="会员名" align="center" prop="userName" />
      <el-table-column label="订单状态" align="center" prop="orderState">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_state" :value="scope.row.orderState"/>
        </template>
      </el-table-column>
      <el-table-column label="收货地址" align="center" prop="fullLocation" />
      <el-table-column label="收货人" align="center" prop="consignee" />
      <el-table-column label="联系电话" align="center" prop="telNumber" />
      <el-table-column label="实际支付金额" align="center" prop="actualPrice" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">

          <!-- 添加详情按钮 -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-info"
            @click="handleDetail(scope.row)"
          >详情</el-button>


          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['order:order:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['order:order:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单信息对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="订单流水号" prop="orderSn">
              <el-input v-model="form.orderSn" placeholder="请输入订单流水号"  :disabled="isEdit"/>
            </el-form-item>

            <el-form-item label="会员名" prop="userName">
              <el-select v-model="form.userName" placeholder="请输入会员名" :disabled="isEdit"  >
              </el-select>
            </el-form-item>

            <el-form-item label="订单状态" prop="orderState">
              <el-select v-model="form.orderState" placeholder="请选择订单状态">
                <el-option
                  v-for="dict in dict.type.order_state"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="快递公司" prop="expressCompany">
              <el-input v-model="form.expressCompany" placeholder="请输入快递公司" />
            </el-form-item>
            <el-form-item label="快递单号" prop="expressNumber">
              <el-input v-model="form.expressNumber" placeholder="请输入快递单号" />
            </el-form-item>
            <el-form-item label="快递费用" prop="expressCost">
              <el-input v-model="form.expressCost" placeholder="请输入快递费用" />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>

      <!-- 详情弹窗 -->
      <el-dialog
        :title="detailTitle"
        :visible.sync="detailOpen"
        width="50%"
        append-to-body
      >
        <el-form ref="detailForm" :model="detailForm" label-width="120px">
          <!-- 订单流水号、会员名 -->
          <el-row>
            <el-col :span="12">
              <el-form-item label="订单流水号">
                <el-input v-model="detailForm.orderSn" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="会员名">
                <el-input v-model="detailForm.userName" disabled />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 订单状态、收货地址 -->
          <el-row>
            <el-col :span="12">
              <el-form-item label="订单状态">
                <el-select v-model="detailForm.orderState" disabled>
                  <el-option
                    v-for="dict in dict.type.order_state"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                  ></el-option>
                </el-select>
                <!-- <el-input v-model="detailForm.orderState" disabled /> -->
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="收货地址">
                <el-input v-model="detailForm.fullLocation" disabled />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 收货人、联系电话 -->
          <el-row>
            <el-col :span="12">
              <el-form-item label="收货人">
                <el-input v-model="detailForm.consignee" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话">
                <el-input v-model="detailForm.telNumber" disabled />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 快递公司、快递单号 -->
          <el-row>
            <el-col :span="12">
              <el-form-item label="快递公司">
                <el-input v-model="detailForm.expressCompany" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="快递单号">
                <el-input v-model="detailForm.expressNumber" disabled />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 快递费用、订单总价 -->
          <el-row>
            <el-col :span="12">
              <el-form-item label="快递费用">
                <el-input v-model="detailForm.expressCost" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="订单总价">
                <el-input v-model="detailForm.orderPrice" disabled />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 实付金额、付款时间 -->
          <el-row>
            <el-col :span="12">
              <el-form-item label="实付金额">
                <el-input v-model="detailForm.actualPrice" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="付款时间">
                <el-input v-model="detailForm.payTime" disabled />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 备注 -->
          <el-row>
            <el-col :span="12">
              <el-form-item label="备注">
                <el-input v-model="detailForm.remark" disabled />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 备注 -->
          <el-row>
            <el-col :span="24" style="text-align: center;">
              <div>订单详情</div>
            </el-col>
          </el-row>

          <!-- 订单详情商品列表 -->

            <el-table style="width: 100%" :data="this.detailList">
              <el-table-column label="编号" prop="tid" />
              <el-table-column label="商品名称" prop="goodsName" />
              <el-table-column label="商品属性" prop="attrsText" />
              <el-table-column label="商品价格" prop="goodsPrice" />
              <el-table-column label="数量" prop="quantity" />
            </el-table>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="detailOpen = false">关 闭</el-button>
        </div>
      </el-dialog>
      <div id="main" style="width: 100%; height: 450px"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { listOrder, getOrserDetail , getShowchars2 , listUser , getOrder, delOrder, addOrder, updateOrder } from "@/api/order/order";

export default {
  name: "Order",
  dicts: ['order_state'],
  data() {
    return {
      userList:[],
      detailOpen: false,
      detailTitle: "订单详情",
      detailList:[],
      detailForm: {
        orderSn: "",
        userName: "",
        orderState: "",
        fullLocation: "",
        consignee: "",
        telNumber: "",
        expressCompany: "",
        expressNumber: "",
        expressCost: 0,
        orderPrice: 0,
        actualPrice: 0,
        payTime: "",
        remark: "",
      },
      // 新增和修改状态标志，true 表示修改，false 表示新增
      isEdit: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单信息表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderSn: null,
        orderState: null,
        userName:null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orderSn: [
          { required: true, message: "订单流水号不能为空", trigger: "blur" }
        ],
        expressCompany: [
          { required: true, message: "快递公司不能为空", trigger: "blur" }
        ],
        expressNumber: [
          { required: true, message: "快递单号不能为空", trigger: "blur" }
        ],
        expressCost: [
          { required: true, message: "快递费用不能为空", trigger: "blur" }
        ],
      }
    };
  },
  mounted(){
      var option = {
          title: {
              text: '订单管理用户',
              subtext: '',
              left: 'center'
          },
          tooltip: {
              trigger: 'item',
              formatter: '{b} : 订单总价{c}元'       //{b}（类目值），{c}（数值）
          },
          xAxis: {
              type: 'category',   //类目轴（category）   强制显示所有X轴数据为文本标签
              data: []   //X轴数据
          },
          yAxis: {
              type: 'value'   //坐标轴类型  'value'，数值轴，适用于连续数据。
          },
          series: [
              {
                  data: [],    //Y轴数据
                  type: 'bar',   //柱状图             换成line变成折线图
                  showBackground: true,   //是否展示背后的背景
                  backgroundStyle: {
                      color: 'rgba(180, 180, 180, 0.2)'    //背景颜色
                  }
              }
          ]
      };
      var chartDom = document.getElementById('main');  //获取显示图表的id对
      var myChart = echarts.init(chartDom);   //echarts.init()初始化图表

      //动态数据对接
      getShowchars2().then(res => {
          console.log(res);
          option.xAxis.data=res.data.x;
          option.series[0].data=res.data.y;
          // 数据准备完毕之后再set
          myChart.setOption(option);
      })
  },
  created() {
    this.getList();
    this.getUserList();
  },
  methods: {
    /** 用户列表*/
    getUserList() {
        listUser().then(response => {
            this.userList = response.rows; // 假设接口返回格式为 { data: [...] }
            console.log(this.userList)
        });
    },

    /** 查询订单信息列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderSn: null,
        userId: null,
        orderState: null,
        addressId: null,
        expressCompany: null,
        expressNumber: null,
        expressCost: null,
        orderPrice: null,
        actualPrice: null,
        payTime: null,
        enabled: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getOrder(id).then(response => {
        this.form = response.data;
        console.log(response.data)
        this.open = true;
        this.title = "修改订单信息";
        // 修改时设置为 true，禁用输入
        this.isEdit = true;

      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDetail(row) {
      const id = row.id;

      getOrserDetail(id).then(response=>{
        this.detailList=response.rows;
        console.log(response);
// console.log(this.detailList);
      });

      getOrder(id).then(response => {
        // 假设后端返回数据结构匹配以下字段
               this.detailForm = {
                 orderSn: response.data.orderSn,
                 userName: response.data.userName,
                 orderState: response.data.orderState,
                 fullLocation: response.data.fullLocation,
                 consignee: response.data.consignee,
                 telNumber: response.data.telNumber,
                 expressCompany: response.data.expressCompany,
                 expressNumber: response.data.expressNumber,
                 expressCost: response.data.expressCost,
                 orderPrice: response.data.orderPrice,
                 actualPrice: response.data.actualPrice,
                 payTime: response.data.payTime,
                 remark: response.data.remark,
            };
// console.log(this.detailForm);
            this.detailOpen=true;
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除订单信息编号为"' + ids + '"的数据项？').then(function() {
        return delOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('order/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
